package com.hy.producer;

import com.hy.entity.Order;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by huangyu on 2018/9/24 15:26
 */
@Component
public class RabbitSender {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	/**
	 * ConfirmCallback
	 */
	final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {

		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String s) {
			System.err.println("correlationData: " + correlationData);
			System.err.println("ack: " + ack);
			if (!ack) {
				System.out.println("异常处理");
			}
		}
	};

	/**
	 * ReturnCallback
	 */
	final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
		@Override
		public void returnedMessage(org.springframework.amqp.core.Message message,
		                            int replyCode, String replyText, String exchange, String routingKey) {
			System.err.println("ReturnCallback: " +
					" exchange:" + exchange +
					" routingKey:" + routingKey +
					" replyCode:" + replyCode +
					" replyText:" + replyText);

		}
	};


	/**
	 * 发送Object类型消息
	 *
	 * @param msg
	 * @param properties
	 */
	public void send(Object msg, Map<String, Object> properties) {
		MessageHeaders messageHeaders = new MessageHeaders(properties);
		Message<Object> message = MessageBuilder.createMessage(msg, messageHeaders);
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		// id设置为全局唯一，一个id对应唯一的一条消息
		CorrelationData correlationData = new CorrelationData();
		correlationData.setId("123456");

		// 测试returnCallback用(消息路由失败调用returnedMessage)
//		rabbitTemplate.convertAndSend("exchange-1", "spring.rk", message, correlationData);
		rabbitTemplate.convertAndSend("exchange-1", "springboot.rk", message, correlationData);

	}


	/**
	 * 生产一个对象实体消息
	 *
	 * @param order
	 */
	public void sendOrder(Order order) {
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		// id设置为全局唯一，一个id对应唯一的一条消息
		CorrelationData correlationData = new CorrelationData();
		correlationData.setId("111111");
		rabbitTemplate.convertAndSend("exchange-2", "springboot.aaa", order, correlationData);

	}
}
